package game;

import card.*;
import game.Player;
import java.util.Stack;
import java.util.ArrayList;
import java.util.Collections;

public class Game {

  Stack<Card> cards;

  public Game () {
    this.cards = new Stack<Card>();

    // assign all unique cards
    for (Color color: Color.values()) {
      for (Value value: Value.values()) {
        cards.push(new Card(color, value));
      }
    }
    System.out.println("deck created");

    // shuffle deck
    Collections.shuffle(cards);
    System.out.println("deck shuffled");
    System.out.println(String.format("%d cards in deck", cards.size()));
}

  // play a round, return winner
  public Player play_round(ArrayList<Player> players) {
    // assign each player a card
    for (Player player: players) {
      player.set_card(cards.peek());
      // if a player got a card from our deck, the card is gone from our deck
      cards.pop();
    }

    // if there is no player, there is no winner
    if (players.size() == 0) {
      return null;
    }

    // if there is only 1 player, we have a winner
    if (players.size() == 1) {
      return players.get(0);
    }

    Player current = players.get(1);
    for (Player player: players) {
      // if player holds a greater card than current
      if (player.get_card().compareTo(current.get_card()) > 0)
        // set new current
        current = player;
    }
    // return highest
    return current;
  }

  public void play(ArrayList<Player> players, int rounds) {
    Player winner;
    // play for <rounds> amount of rounds
    for (int i = 0; i < rounds; i++) {
      // print current round
      System.out.println(String.format("round number %d", i + 1));

      // if there are no cards left in deck
      if (this.cards.size() == 0) {
        System.out.println("no cards left in deck");
      }

      // play a round, assign winner and announce the lucky bastard's name
      winner = play_round(players);
      winner.win();
      System.out.println(String.format("and the winner is %s", winner.get_name()));
      System.out.println(String.format("using a %s", winner.get_card().to_string()));
    }

    // print final results
    System.out.println(" -- FINAL RESULTS --");

    for (Player player: players) {
      System.out.println(String.format("%s: %d wins", player.get_name(), player.won()));
    }
  }
}
